#coding=utf-8
import threading 
from stockdb.misc import *
from sdsource.web.exception import NoDealError
from moneyflow import *

def download_deal(code, start, end=None):
    '''下载某一只股票在一段时间内的所有成交明细数据, 并将数据放入csv文件''' 
    s = find_stock(code)
    
    if end:
        tds = s.tds_between(start, end)
    else:
        tds = s.tds_since(start)
    
    if len(tds) == 0 :
        #print "%s:没有交易 since %s."%(code, start)
        return
        
    eds = [t.date.isoformat() for t in tds]
    for ed in eds:
        
        if deal_exists(code, ed):
            continue
        try:
            download2csv(code, ed)
        except NoDealError,e:
            print "%s:No Deal on %s."%(code, ed)
            continue        
            
class DealDownloader_Thread(threading.Thread):
    def __init__(self, id_, codes, start, end=None):
        threading.Thread.__init__(self)
        
        self.id = id_

        self.codes = codes
        
        self.start_date = start
        self.end_date = end
        
    def run(self):
        print  "线程%i启动."%self.id
        
        for c in self.codes:
            download_deal(c, self.start_date, self.end_date)
            #print "线程%i:完成下载%s的成交明细"%(self.id, c)
            
        print  "线程%i结束."%self.id    


if __name__ == '__main__':
    
    start = '2008-02-20'
    end = '2008-04-10'
    thread_num = 10
    
    codes = get_stcodes()
    step = len(codes)/thread_num + 1
    for i in range(thread_num):
        cs = codes[i*step: (i+1)*step]
        dt = DealDownloader_Thread(i, cs, start, end)
        dt.start()
    
    print "主线程退出."
